package com.shoujifeng.snowmusic.player;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;

import com.geniuseoe2012.lazyloaderdemo.cache.ImageLoader;
import com.shoujifeng.snowmusic.db.DatabaseUtil;
import com.shoujifeng.snowmusic.entity.AnimaAccess;
import com.shoujifeng.snowmusic.player.R;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.http.ServerAccess;
import com.shoujifeng.snowmusic.player.utils.LoadMask;
import com.shoujifeng.snowmusic.player.utils.MusicPlayer;

public class OnlineSearch extends Activity {
	private ListView mListView;
	private RankingListAdapter mAdapter;
	private Button searchbuttonclear;
	private ArrayList<HashMap<String, Object>> mSpecialList;
	private ArrayList<HashMap<String, Object>> mMusicList;
	private LayoutInflater inflater;
	private DisplayMetrics dm;
	private ImageButton breakBtn;
	private EditText onlineSearchEdt;
	private final int UPDATE_THREE = 3;
	private ImageLoader mImageLoader;

	private ServerAccess serverAccess;
	private Thread accThread;

	private String content; //
	private LoadMask mLoadMask;
	
	private boolean bConllectHave = false;
	private boolean bDownloadHave = false;
	
	private DatabaseUtil mDB;
	
	//上一次点击的MoreView
		private View mLastMore;
		
		//收藏
				private boolean bHave;
				private int nindex;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.online_serach);
		init();
		initGlobalValue();
		mLoadMask = new LoadMask(this);
		mLoadMask.startLoad();
		accThread = new Thread(runnable);
		accThread.start();
		
		mDB = new DatabaseUtil(this);
		
		ShareSDK.initSDK(this);
		
	}
	
	@Override
	protected void onDestroy() {
		ShareSDK.stopSDK(this);
		super.onDestroy();
	}

	private void init() {
		mImageLoader = new ImageLoader(OnlineSearch.this);
		content = getIntent().getExtras().getString("content");
		serverAccess = new ServerAccess(OnlineSearch.this);
		mListView = (ListView) findViewById(R.id.my_collect_single_list);
		onlineSearchEdt = (EditText) findViewById(R.id.onlineSearchEdt);

		breakBtn = (ImageButton) findViewById(R.id.breakBtn);
		breakBtn.setOnClickListener(onClickListener);

		searchbuttonclear = (Button) findViewById(R.id.searchbuttonclear);
		searchbuttonclear.setOnClickListener(onClickListener);
		mListView.setOnItemClickListener(itemClickListener);
		
		onlineSearchEdt.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				
				if(actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
					
					((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(
							OnlineSearch.this.getCurrentFocus().getWindowToken(), 
							InputMethodManager.HIDE_NOT_ALWAYS);   
					
					content = onlineSearchEdt.getText().toString();
					if(content.equals("")){
						Toast.makeText(OnlineSearch.this, "搜索内容不能为空",Toast.LENGTH_SHORT).show();
					}
					else{
						accThread = new Thread(runnable);
						accThread.start();
					//	mAdapter.notifyDataSetChanged();	
					}
					
				}
				
				return false;
			}
		});

	}

	private OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long arg3) {
			
			if (position < mSpecialList.size()) {
				Intent intent = new Intent(OnlineSearch.this,
						OnlineSpecialContentActivity.class);
				intent.putExtra(ServerAccess.ALBUM,
						mSpecialList.get(position ).get(ServerAccess.ALBUM)
								.toString());
				intent.putExtra(ServerAccess.INDEX,
						mSpecialList.get(position ).get(ServerAccess.INDEX)
								.toString());
				startActivity(intent);
				
				overridePendingTransition(R.anim.right_in, R.anim.left_out);
			}
			else {
				Intent intent = new Intent(OnlineSearch.this, MusicPlayerActivity.class);
				MusicPlayerActivity.mOlineMusicList = mMusicList;
				MusicPlayer.position = position - mSpecialList.size();
				MusicPlayerActivity.isOnline = true ;
				 MusicPlayer.MUSCI_MSG =1;
				startActivity(intent);
				
				overridePendingTransition(R.anim.bottom_in,android.R.anim.fade_out);
			}
		}
	};

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.breakBtn:
				finish();
				overridePendingTransition(R.anim.no_move, R.anim.right_out);
				break;
			case R.id.searchbuttonclear: {
				content = onlineSearchEdt.getText().toString();
				if(content.equals("")){
					Toast.makeText(OnlineSearch.this, "搜索内容不能为空",Toast.LENGTH_SHORT).show();
				}
				else{
					accThread = new Thread(runnable);
					accThread.start();
				//	mAdapter.notifyDataSetChanged();	
				}
				
			}
			default:
				break;
			}
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
		{
			finish();
			
			overridePendingTransition(R.anim.no_move, R.anim.right_out);
		}
			break;

		default:
			break;
		}
		
		return super.onKeyDown(keyCode, event);
	}

	private class RankingListAdapter extends BaseAdapter {
		ArrayList<HashMap<String, Object>> specialList;
		ArrayList<HashMap<String, Object>> musicList;
		final int TYPE_1 = 0;
		final int TYPE_2 = 1;
		Context mContext;
		LayoutInflater inflater;

		public RankingListAdapter(
				ArrayList<HashMap<String, Object>> mSpecialList,
				ArrayList<HashMap<String, Object>> mMusicList, Context context) {
			// TODO Auto-generated constructor stub
			this.specialList = mSpecialList;
			this.musicList = mMusicList;
			mContext = context;
			inflater = LayoutInflater.from(mContext);
		}

		public int getCount() {
			return specialList.size() + musicList.size();
		}

		public Object getItem(int position) {

			return specialList.get(position);
		}

		public long getItemId(int position) {

			return position;
		}

		@Override
		public int getItemViewType(int position) {
			// TODO Auto-generated method stub
			if (position < specialList.size()) {
				return TYPE_1;
			} else {
				return TYPE_2;
			}
		}

		@Override
		public int getViewTypeCount() {
			// TODO Auto-generated method stub
			return 2;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder01 holder01 = null;
			ViewHolder02 holder02 = null;
			
			int type = getItemViewType(position);
			if (convertView == null) {
				switch (type) {
				case TYPE_1:
					convertView = inflater.inflate(
							R.layout.onlie_search_special, parent, false);

					holder01 = new ViewHolder01();
					holder01.specialSpecialName = (TextView) convertView
							.findViewById(R.id.specialName);
					holder01.musicSpecialName = (TextView) convertView
							.findViewById(R.id.musicName);
					holder01.face = (ImageView) convertView.findViewById(R.id.face);
					convertView.setTag(holder01);

					HashMap<String, Object> map = new HashMap<String, Object>();
					map = specialList.get(position);
					holder01.specialSpecialName.setText(map.get(
							ServerAccess.ALBUM).toString());
					holder01.musicSpecialName.setText(map.get(
							ServerAccess.SINGER).toString());
					mImageLoader.DisplayImage(map.get(ServerAccess.ICON_URL).toString(), holder01.face, false, R.drawable.icon_album_default);

					break;
				case TYPE_2:
					convertView = inflater.inflate(
							R.layout.online_search_music, parent, false);

					holder02 = new ViewHolder02();
					holder02.musicMusicName = (TextView) convertView
							.findViewById(R.id.musicName);
					holder02.musicPlayerName = (TextView) convertView
							.findViewById(R.id.playerName);
					holder02.typeText = (TextView) convertView.findViewById(R.id.type);
					convertView.setTag(holder02);

					HashMap<String, Object> map2 = new HashMap<String, Object>();
					map2 = musicList.get(position - specialList.size());
					holder02.musicMusicName.setText(map2.get(
							ServerAccess.MUSIC_NAME).toString());
					holder02.musicPlayerName.setText(map2.get(
							ServerAccess.SINGER).toString());
					if(map2.get(ServerAccess.LAN).equals("3366")){
						holder02.typeText.setText("藏");
					}
					
					
					ImageView imgMore = (ImageView) convertView.findViewById(R.id.moreImg);
					
					//设置弹出菜单
					if(imgMore != null)
					{ 
						//得到弹出菜单， 将Pos储存
						View moreView = (View)convertView.findViewById(R.id.music_more_lay);
						moreView.setTag(position - specialList.size());
						
						//将弹出菜单存到按钮里
						imgMore.setTag(moreView);
						imgMore.setOnClickListener(moreOnClickListener);
						
						//隐藏所有弹出菜单
						moreView.setVisibility(View.GONE);
						if(mLastMore != null)
						{	
							mLastMore.setVisibility(View.GONE);
							mLastMore = null;
						}
						
						//添加相关点击
						Button btnDownload = (Button)moreView.findViewById(R.id.onHotList_btn_download);
						Button btnConllect = (Button)moreView.findViewById(R.id.onHotList_btn_conllect);
						Button btnShare = (Button)moreView.findViewById(R.id.onHotList_btn_share);
						btnDownload.setTag(position - specialList.size());
						btnConllect.setTag(position - specialList.size());
						btnShare.setTag(position - specialList.size());
						btnDownload.setOnClickListener(downloadOnClickListener);
						btnConllect.setOnClickListener(conllectOnClickListener);
						btnShare.setOnClickListener(shareOnClickListener);
						
					}
					
					break;

				}

			} else {
				switch (type) {
				case TYPE_1:
					holder01 = (ViewHolder01) convertView.getTag();
					break;
				case TYPE_2:
					holder02 = (ViewHolder02) convertView.getTag();
					break;

				}
			}

			return convertView;
		}

		//更多按下
				private View.OnClickListener moreOnClickListener = new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {

						View moreView = (View)v.getTag();
						
						//如果上一次点击了菜单， 隐藏之
						if(mLastMore != null) {
							mLastMore.setVisibility(View.GONE);
						}
						int index = Integer.parseInt(moreView.getTag().toString());
						
						Button btnDownload = (Button)moreView.findViewById(R.id.onHotList_btn_download);
						Button btnConllect = (Button)moreView.findViewById(R.id.onHotList_btn_conllect);
						
						HashMap<String, Object> map = musicList.get(index);
						
						int uid = Integer.parseInt(map.get("index").toString());
						bConllectHave = mDB.haveConllect(uid);
						
						if(bConllectHave) {
							btnConllect.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.btn_collect_have));
						}
						else {
							btnConllect.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.onlinelike));
						}
						
						bDownloadHave = mDB.haveDownload(uid);
						if(bDownloadHave) {
							btnDownload.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.btn_download_have));
						}
						else {
							btnDownload.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.onlinedownload));
						}
						
						
						//滑动动画
						AnimaAccess anim = new AnimaAccess(mContext);
						moreView.startAnimation(anim.alphaAnimation(0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 200, false));
						
						moreView.setVisibility(View.VISIBLE);
						
						//储存这次按下的菜单
						mLastMore = moreView;
					}
				};
				
				//下载按下
				private View.OnClickListener downloadOnClickListener = new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						int position = Integer.parseInt(v.getTag().toString());
						
						HashMap<String, Object> map = mMusicList.get(position);
						
						GlobalValue.g_DownloadManager.addDownload(map);
						
						Toast.makeText(OnlineSearch.this, "已加入下载!", Toast.LENGTH_LONG).show();
						
						mLastMore.setVisibility(View.GONE);
					}
				};
				
				//收藏按下
					private View.OnClickListener conllectOnClickListener = new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							
							int position = Integer.parseInt(v.getTag().toString());
							
							if(ServerAccess.uid > 0) {
								
								HashMap<String, Object> map = mMusicList.get(position);
								int index = Integer.parseInt(map.get(ServerAccess.INDEX).toString());
								
								OnlineSearch.this.nindex = index;
								
								bHave = bConllectHave;
								if(!bConllectHave) {
									//写入本地
									mDB.insertConllect(index, ServerAccess.uid);
									
									//写入网络
									Thread thread = new Thread(delRunnable);
									thread.start();
									
									//收藏成功
									Toast.makeText(OnlineSearch.this, "收藏成功!", Toast.LENGTH_LONG).show();
								}
								else {
									mDB.deleteConllect(index);
									
									//写入网络
									Thread thread = new Thread(delRunnable);
									thread.start();
									
									Toast.makeText(OnlineSearch.this, "已删除收藏!", Toast.LENGTH_LONG).show();
								}
							}
							else {
								//跳登陆
								Intent intent = new Intent(OnlineSearch.this,
										LoginActivity.class);
								startActivity(intent);
								
								overridePendingTransition(R.anim.right_in, R.anim.left_out);
							}
							
							mLastMore.setVisibility(View.GONE);
						}
					};
					//分享按下
							private View.OnClickListener shareOnClickListener = new View.OnClickListener() {
								
								@Override
								public void onClick(View v) {
									
									int position = Integer.parseInt(v.getTag().toString());
									
									HashMap<String, Object> map = mMusicList.get(position);
									
									OnekeyShare oks = new OnekeyShare();

									// 分享时Notification的图标和文字
									oks.setNotification(R.drawable.ic_launcher, 
									"分享");
									// text是分享文本，所有平台都需要这个字段
									oks.setText("我在雪域音乐App上发现一首很好听的歌<" + map.get(ServerAccess.MUSIC_NAME).toString() 
											+ "> 分享给大家听听。");

									// 是否直接分享（true则直接分享）
									oks.setSilent(false);

									// 去除注释可通过OneKeyShareCallback来捕获快捷分享的处理结果
									// oks.setCallback(new OneKeyShareCallback());
									//通过OneKeyShareCallback来修改不同平台分享的内容
									oks.setShareContentCustomizeCallback(
									new ShareContentCustomizeCallback() {
										
										@Override
										public void onShare(Platform platform, ShareParams paramsToShare) {
											// TODO Auto-generated method stub
											
										}
									});

									oks.show(OnlineSearch.this);
									
									mLastMore.setVisibility(View.GONE);
								}
							};
	}
	
	
	//删除收藏
			//BY Kress
			protected Runnable delRunnable = new Runnable() {
				
				@Override
				public void run() {
					try {
						ServerAccess serverAccess = new ServerAccess(OnlineSearch.this);
						if(bHave) {
							serverAccess.delToConllect(nindex, ServerAccess.uid, new String[]{});
						}
						else {
							serverAccess.addToConllect(nindex, ServerAccess.uid, new String[]{});
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			};

	class ViewHolder01 {
		TextView specialSpecialName;
		TextView musicSpecialName;
		ImageView face;
	}

	class ViewHolder02 {
		TextView musicMusicName;
		TextView musicPlayerName;
		TextView typeText;
	}

	protected Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case UPDATE_THREE: {
				mLoadMask.stopLoad();
				setListView();
			}
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	// 
	protected Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				
					String keys[] = new String[] { ServerAccess.ALBUM,
							ServerAccess.LISTENER, ServerAccess.SINGER,
							ServerAccess.ICON_URL, ServerAccess.INDEX };
					mSpecialList = new ArrayList<HashMap<String, Object>>();
					mSpecialList = serverAccess.getAlbumListAtSearch(keys, content);

					String keys2[] = new String[] { ServerAccess.MUSIC_NAME,
							ServerAccess.LISTENER, ServerAccess.SINGER,
							ServerAccess.ICON_URL, ServerAccess.INDEX,
							ServerAccess.CODE, ServerAccess.MUSIC_FILE,
							ServerAccess.LAN,
							ServerAccess.ARTIST_ID ,ServerAccess.ALBUM};
					mMusicList = new ArrayList<HashMap<String, Object>>();
					mMusicList = serverAccess.getMusicListAtSearch(keys2, content);

					sendMessage(UPDATE_THREE);
				
				
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	};

	// 
	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	private void initGlobalValue() {
		GlobalValue.initSDAddr();

		GlobalValue.addUrl(ServerAccess.SEARCH,
				"http://www.snowmusic.com.cn/mobile_api/search.php");
	}

	private void setListView() {
		mAdapter = new RankingListAdapter(mSpecialList, mMusicList,
				OnlineSearch.this);
		mListView.setAdapter(mAdapter);
	}

}
